﻿$(function () {
    var assetTypeArray = [];
    //点击链接弹出窗口
    $("input[type='button'].addUpdateAsset").live("click", function () {
        cleanForm();
        $("div.popupWindow").show("slow");
        var btnCurrent = this;
        $.ajax({
            url: "../../asset/getAllUsers",
            type: "get",
            dataType: "json",
            success: function (data) {
                $("#assetBelongsTo").empty();
                var $parent = $(btnCurrent).parent().parent();
                var owner = $.trim($("td:eq(5)", $parent).text());
                $.each(data.employees, function (i, item) {
                    if (btnCurrent.name == "update") {
                        if (owner == item.alias) {
                            $("#assetBelongsTo").append("<option value='" + item.alias + "' selected='selected'>" + item.alias + "</option>");
                        } else {
                            $("#assetBelongsTo").append("<option value='" + item.alias + "'>" + item.alias + "</option>");
                        }
                    } else {
                        $("#assetBelongsTo").append("<option value='" + item.alias + "'>" + item.alias + "</option>");
                    }
                });
            }
        });
        $.ajax({
            url: "../../asset/getAssetTypes",
            type: "get",
            dataType: "json",
            success: function (data) {
                $("#selAssetType").empty();
                if (data.types) {
                    $("#selAssetType").append("<option value='0'>请选择...</option>");
                    var $parent = $(btnCurrent).parent().parent();
                    var type = $.trim($("td:eq(3)", $parent).text());
                    var isFirst = (assetTypeArray.length == 0);
                    $.each(data.types, function (i, item) {
                        if (isFirst) assetTypeArray.push({ "type": item.type, "b": item.hasNIC });
                        if (btnCurrent.name == "update") {
                            if (type == item.type) {
                                $("#selAssetType").append("<option value='" + item.type + "' selected='selected'>" + item.type + "</option>");
                            } else {
                                $("#selAssetType").append("<option value='" + item.type + "'>" + item.type + "</option>");
                            }
                        } else {
                            $("#selAssetType").append("<option value='" + item.type + "'>" + item.type + "</option>");
                        }
                    });
                }
                if (btnCurrent.name == "update") {
                    $("#selAssetType").attr("disabled", "true");
                }
                else {
                    $("#selAssetType").removeAttr("disabled"); ;
                }
            }
        });
        if (this.name == "update") {
            $("h2:eq(0)", $("div.popupWindow")).attr("id", "updateAssetTitle").html("更新资产信息");
            $("input#assetID").attr("readonly", true);
            var $parent = $(this).parent().parent();
            $("input#assetID").val($.trim($("td:eq(1)", $parent).text()));
            $("input#assetModel").val($.trim($("td:eq(2)", $parent).text()));
            $("input#assetSn").val($.trim($("td:eq(4)", $parent).text()));
            $("#assetDescription").val($.trim($("td:eq(6)", $parent).text()));
            $("select#assetType").find("option[value='" + $.trim($("td:eq(3)", $parent).text()) + "']").attr("selected", true);
            $.ajax({
                url: "../../asset/getMACByAssetID",
                type: "get",
                data: { "assetID": $("input#assetID").val() },
                dataType: "json",
                success: function (data) {
                    $("#iptMAC").empty();
                    $.each(data.MAC, function (i, item) {
                        $("#iptMAC").val(item.MAC);
                    });
                }
            });
        } else {
            $("h2:eq(0)", $("div.popupWindow")).attr("id", "newAddAssetTitle").html("添加新的资产");
            $("input#assetID").removeAttr("readonly");
            $("input#assetID").val("");
            $("input#iptMAC").val("");
        }
        $("#assetID").focus();
        //获取页面文档的高度
        var docheight = $(document).height();
        //追加一个层，使背景变灰
        $("#greybackground").css({ "opacity": "0.5", "height": docheight });
        $("#greybackground").show();
        return false;
    });
    //asset type change event
    $("select#selAssetType").change(function () {
        if (this.value == "0" || $("h2:eq(0)", $("div.popupWindow")).attr("id") == "updateAssetTitle") {
            $("input#iptMAC").attr("readonly", "readonly");
        } else {
            for (var v in assetTypeArray) {
                if (assetTypeArray[v]["type"] == this.value) {
                    if (assetTypeArray[v]["b"] == 'True') {
                        $("input#iptMAC").removeAttr("readonly");
                        $("input#iptMAC").focus();
                    } else {
                        $("input#iptMAC").attr("readonly", "readonly")
                        $("input#iptMAC").val("");
                    }
                    break;
                }
            }
        }
    });
    //提交表单
    $("input#btnSubmit").click(function () {
        if ($("input#assetID").val() == "") {
            $("span", $("input#assetID").parent()).text("Asset ID不能为空！");
            return false;
        }
        if ($("input#assetModel").val() == "") {
            $("span", $("input#assetModel").parent()).text("Asset型号不能为空！");
            return false;
        }
        if ($("#selAssetType option:selected").val() == "0") {
            $("span", $("#selAssetType").parent()).text("请选择资产类别！");
            return false;
        }
        var hasNIC;
        for (var v in assetTypeArray) {
            if (assetTypeArray[v]["type"] == $("#selAssetType option:selected").val()) {
                hasNIC = assetTypeArray[v]["b"];
                if (hasNIC == 'True' && $("h2:eq(0)", $("div.popupWindow")).attr("id") != "updateAssetTitle") {
                    var reg_MAC = /[A-F\d]{2}[:-][A-F\d]{2}[:-][A-F\d]{2}[:-][A-F\d]{2}[:-][A-F\d]{2}[:-][A-F\d]{2}/;
                    if (!reg_MAC.test($("input#iptMAC").val())) {
                        $("span", $("#iptMAC").parent()).text("MAC值格式不正确！");
                        return false;
                    }
                }
            }
        }
        var requestUrl = "../../asset/submit";
        if ($("h2:eq(0)", $("div.popupWindow")).attr("id") == "updateAssetTitle") {
            requestUrl = "../../asset/update";
        }
        $.ajax({
            url: requestUrl,
            type: "POST",
            data: { "MAC": $("input#iptMAC").val(), "hasNIC": hasNIC, "assetID": $("input#assetID").val(), "model": $("input#assetModel").val(), "type": $("select#selAssetType option:selected").text(), "Sn": $("input#assetSn").val(), "description": $("#assetDescription").val(), "owner": $("select#assetBelongsTo option:selected").text() },
            dataType: "json",
            success: function (data) {
                switch (data.status) {
                    case 1:
                        $("span", $("input#assetID").parent()).text("Asset ID已经存在！");
                        break;
                    case 2:
                        $("div.popupWindow").hide();
                        $("#greybackground").hide();
                        alert("操作成功！");
                        window.location.reload();
                        //                                $("<tr><td>" + $("input#assetID").val() + "</td><td>" + $("input#assetModel").val() + "</td><td>" + $("select#assetType option:selected").text() + "</td><td>" + $("input#assetSn").val() + "</td><td>" + $("select#assetBelongsTo option:selected").text() + "</td><td>" + $("#assetDescription").val() + "</td><td><input class=\"addUpdateAsset\" id=\"btnUpdate\" type=\"button\" name=\"update\" value=\"修改\" /></td></tr>").insertBefore($("#tblMain tr:eq(1)"));
                        break;
                    case 4:
                    default:
                        alert("出错啦，联系管理员！");
                        break;
                }
            }
        });
    });
    //清空表单
    $("input#btnReset").click(function () {
        cleanForm();
    });
    //删除选中资产
    $("input#btnDelete").click(function () {
        if ($("input[type='checkbox']:checked", $("#tblMain tr td")).length == 0) {
            alert("请选择需要删除的asset");
            return;
        }
        if (confirm("确定删除选中的" + $("input[type='checkbox']:checked", $("#tblMain tr td")).length + "项asset?")) {
            var queryData = "";
            var ids = $("input[type='checkbox']:checked", $("#tblMain tr td"));
            $.each(ids, function (i, item) {
                if (i == 0) {
                    queryData = item.id;
                } else {
                    queryData += '||' + item.id;
                }
            });
            $.ajax({
                url: "../../asset/delete",
                type: "POST",
                data: { "ids": queryData },
                dataType: "json",
                success: function (data) {
                    switch (data.status) {
                        case 2:
                            alert("操作成功！");
                            window.location.reload();
                            break;
                        case 4:
                        default:
                            alert("出错啦，联系管理员！");
                            break;
                    }
                }
            });
        }
    });
    function cleanForm() {
        if ($("input#assetID").attr("readonly") != true) $("input#assetID").val("");
        $("input#assetModel").val("");
        $("input#assetSn").val("");
        $("#assetDescription").val("");
        $("span", $("#iptMAC").parent()).text("")
        $("span", $("input#assetID").parent()).text(" *");
        $("span", $("input#assetModel").parent()).text(" *");
        $("span", $("#selAssetType").parent()).text(" *");
    }
});